import {h} from 'vue';
import {guid} from '@/utils';
import FormComponentDelegate from '@comp/FormEngine/FormComponentDelegate.vue';

export default {
  render(context) {
    let templateConfigs = this.getTemplateConfigs(context), res = [];
    context?.buildModelIfNecessary();

    templateConfigs.forEach(config => {
      res.push(h(FormComponentDelegate, {
        config,
        context
      }));
    });
    return this.createFormViewWrapper(context, res);
  },

  getTemplateConfigs(context) {
    let res = context.templateConfigs || [];
    try {
      let viewRedirect = context.formModel && context.formModel._viewRedirect || {};
      if (viewRedirect[context.viewId]) {
        let newViewId = viewRedirect[context.viewId];
        let view = context.formDefinition.views.find(v => v.id === newViewId);
        if (view) {
          return view.templateConfigs;
        }
      }
      // console.log('没有找到视图重定向呢', context.viewId, viewRedirect)
    } catch (e) {
      console.error(e);
    }
    return res;
  },

  createFormViewWrapper(context, list) {
    let width = `${context.view && context.view.pageWidth || 0}px`;
    let padding = `${context.view && context.view.padding || '10px'}`;

    try {
      let viewId = (context.formModel && context.formModel._viewRedirect || {})[context.viewId];
      if (viewId) {
        let view = (context.formDefinition.views || []).find(v => v.id === viewId);
        if (view) {
          width = `${view.pageWidth || 0}px`;
          padding = `${view.padding || '10px'}`;
        }
      }
    } catch (e) {

    }

    return h('div', {
      class: 'form-engine-view',
      attrs: {
        'form-name-space': context.formNameSpace || guid()
      },
      key: `${context.viewId}-${context.actionId}`,
      style: {
        // width: width,
        // padding: padding
      }
    }, list);
  }
};